# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/11/11 14:01
# @Author  : zuodengbo
# @Email   : zuodb@amoydx.com
# @File    : redis_utils
# @Software: PyCharm
import socket

import asyncio_redis
import asyncio
from config import RedisConfig


class Redis(object):
    """
    Redis object
    """
    _pool = None

    async def redis_pool(self):
        """
        Create redis pool
        :return:
        """
        if not self._pool:
            try:
                self._pool = await asyncio_redis.Pool.create(
                    host=RedisConfig.host, port=RedisConfig.port, password=RedisConfig.password,
                    db=RedisConfig.db, poolsize=RedisConfig.pool_size
                )
            except socket.timeout:
                print("Redis connection timeout")
            except Exception as e:
                print("Something happened when connect redis: {}".format(e))

        return self._pool

    def close(self):
        """
        Close redis pool
        :return:
        """
        if self._pool:
            self._pool.close()


sanic_redis = Redis()


async def main():

    rp = await sanic_redis.redis_pool()
    k = "E_name"
    f = "n"
    v = "Borden"
    # await rp.hset(k, f, v)
    # val = await rp.hget(k, f)
    # await rp.set(k, v, expire=60)
    val = await rp.get(k)
    print(val)
    sanic_redis.close()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
